﻿using BotDetector.Core.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace BotDetector.Core.NaiveBayesModule
{
    public class BayesFileOperator
    {
        private string CLASSIFIER_SERIALIZATION_FILE;
        private string CLASSIFIER_SERIALIZATION_TRAIN_FILE;
        private string NONBOT_FOLDER_PATH;
        private string BOT_FOLDER_PATH;
        private string BOT_LABEL = Constants.BotLabel;
        private string NONBOT_LABEL = Constants.NonbotLabel;

        private FileOperator fileReader = new FileOperator(); 

        public BayesFileOperator()
        {
            string rootPath = Path.GetDirectoryName(Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory));
            CLASSIFIER_SERIALIZATION_FILE = rootPath + Constants.BayesClassifierPath;
            CLASSIFIER_SERIALIZATION_TRAIN_FILE = rootPath + Constants.BayesClassifierTrainPath;
            NONBOT_FOLDER_PATH = rootPath + Constants.NonbotTrainPath;
            BOT_FOLDER_PATH = rootPath + Constants.BotTrainPath;
        }

        public List<Document> GetNonbotDocumentSet()
        {
            return GetDocumentSet(NONBOT_FOLDER_PATH, NONBOT_LABEL);
        }

        public List<Document> GetBotDocumentSet()
        {
            return GetDocumentSet(BOT_FOLDER_PATH, BOT_LABEL);
        }

        public List<Document> GetDocumentSet(string folderPath, string label)
        {
            List<Document> documentList = new List<Document>();
            List<string> filesContent = fileReader.ReadFileSet(folderPath);

            foreach(string x in filesContent)
            {
                documentList.Add(new Document(label, x));
            }

            return documentList;
        }

        public void SaveClassifier(BayesClassifier classifier)
        {
            FileStream stream = File.Create(CLASSIFIER_SERIALIZATION_TRAIN_FILE);
            var formatter = new BinaryFormatter();
            formatter.Serialize(stream, classifier);
            stream.Close();
        }

        public BayesClassifier ReadClassifier()
        {
            FileStream stream = File.OpenRead(CLASSIFIER_SERIALIZATION_FILE);
            var formatter = new BinaryFormatter();
            var classifier = (BayesClassifier)formatter.Deserialize(stream);
            stream.Close();

            return classifier;
        }
    }
}
